﻿#include "UIIpcClient.h"

#include "ui_msg_def.h"
#include <algorithm>
#include <cstring>
#include <windows.h>



bool UIIpcClient::init() {
    return connect();
}

void UIIpcClient::release() {
    disconnect();
}


UIIpcClient::UIIpcClient()
: _hPipe(INVALID_HANDLE_VALUE),
_ipc_msg_helper(this){

}

UIIpcClient::~UIIpcClient() {
    disconnect();
}

bool UIIpcClient::connect() {
    if (_hPipe != INVALID_HANDLE_VALUE) return true;
    
    _hPipe = CreateFileA(
        UI_PIPE_NAME,
        GENERIC_READ |  // read and write access 
        GENERIC_WRITE, 
        0,              // no sharing 
        NULL,           // default security attributes
        OPEN_EXISTING,  // opens existing pipe 
        0,              // default attributes 
        NULL);          // no template file 

    if (_hPipe == INVALID_HANDLE_VALUE) 
        return false; 

    // The pipe connected; change to message-read mode. 
 
    DWORD dwMode = PIPE_READMODE_MESSAGE; 
    BOOL fSuccess = SetNamedPipeHandleState( 
      _hPipe,    // pipe handle 
      &dwMode,  // new pipe mode 
      NULL,     // don't set maximum bytes 
      NULL);    // don't set maximum time 

    if (!fSuccess) 
    {
      CloseHandle(_hPipe); 
      _hPipe = INVALID_HANDLE_VALUE;
      return false;
    } 
    return true;
}

void UIIpcClient::disconnect() {
    if (_hPipe != INVALID_HANDLE_VALUE) {
        CloseHandle(_hPipe);
        _hPipe = INVALID_HANDLE_VALUE;
    }
}


bool UIIpcClient::sendBuffer(const void *data,int len,DWORD *written){
    
    if (_hPipe == INVALID_HANDLE_VALUE) {
        //连接
        if(!connect()){
            return false;
        }
    }

    bool ret = WriteFile(_hPipe, data, len, written, NULL);
    if(!ret){
        //重新连接
        disconnect();
        if(!connect()){
            return false;
        }

        //再试一次
        ret = WriteFile(_hPipe, data, len, written, NULL);
    }

    return ret;
}

bool UIIpcClient::readBuffer(char *buffer,int buffer_size,DWORD *read){
     
    if (!ReadFile(_hPipe, buffer, buffer_size, read, NULL))
    {
        return false;
    }
    return true;
}